using ERPBackend.Data;
using ERPBackend.Models;
using ERPBackend.Services;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ERPBackend.Services
{
    public class SalesContractService : ISalesContractService
    {
        private readonly ApplicationDbContext _context;

        public SalesContractService(ApplicationDbContext context)
        {
            _context = context;
        }

        public async Task<List<SalesContract>> GetAllSalesContractsAsync()
        {
            return await _context.SalesContracts
                .Include(sc => sc.SalesContractItems)
                .Include(sc => sc.Customer)
                .ToListAsync();
        }

        public async Task<SalesContract> GetSalesContractByIdAsync(int id)
        {
            return await _context.SalesContracts
                .Include(sc => sc.SalesContractItems)
                .Include(sc => sc.Customer)
                .FirstOrDefaultAsync(sc => sc.Id == id);
        }

        public async Task<SalesContract> CreateSalesContractAsync(SalesContract salesContract)
        {
            // 确保合同编码唯一
            if (await _context.SalesContracts.AnyAsync(sc => sc.ContractCode == salesContract.ContractCode))
            {
                throw new Exception("合同编码已存在");
            }

            // 设置默认状态为待审核
            if (salesContract.Status != 0)
            {
                salesContract.Status = 0;
            }

            // 计算合同总金额和未收款金额
            if (salesContract.SalesContractItems != null && salesContract.SalesContractItems.Any())
            {
                salesContract.TotalAmount = salesContract.SalesContractItems.Sum(sci => sci.TotalAmount);
                salesContract.UnpaidAmount = salesContract.TotalAmount;
                salesContract.ReceivedAmount = 0;

                // 设置行号
                for (int i = 0; i < salesContract.SalesContractItems.Count; i++)
                {
                    salesContract.SalesContractItems[i].LineNumber = i + 1;
                }
            }

            _context.SalesContracts.Add(salesContract);
            await _context.SaveChangesAsync();

            return salesContract;
        }

        public async Task<bool> UpdateSalesContractAsync(SalesContract salesContract)
        {
            var existingContract = await _context.SalesContracts
                .Include(sc => sc.SalesContractItems)
                .FirstOrDefaultAsync(sc => sc.Id == salesContract.Id);

            if (existingContract == null)
            {
                return false;
            }

            // 检查合同状态，如果已审核或已终止则不允许修改
            if (existingContract.Status == 1 || existingContract.Status == 2)
            {
                throw new Exception("已审核或已终止的合同不能修改");
            }

            // 检查合同编码是否已被其他合同使用
            if (existingContract.ContractCode != salesContract.ContractCode &&
                await _context.SalesContracts.AnyAsync(sc => sc.ContractCode == salesContract.ContractCode))
            {
                throw new Exception("合同编码已存在");
            }

            // 更新合同信息
            _context.Entry(existingContract).CurrentValues.SetValues(salesContract);

            // 处理合同明细
            // 删除已移除的明细
            var existingItems = existingContract.SalesContractItems.ToList();
            foreach (var existingItem in existingItems)
            {
                if (!salesContract.SalesContractItems.Any(sci => sci.Id == existingItem.Id))
                {
                    _context.SalesContractItems.Remove(existingItem);
                }
            }

            // 添加或更新明细
            foreach (var item in salesContract.SalesContractItems)
            {
                if (item.Id == 0)
                {
                    // 新明细
                    item.SalesContractId = salesContract.Id;
                    _context.SalesContractItems.Add(item);
                }
                else
                {
                    // 更新现有明细
                    var existingItem = existingItems.FirstOrDefault(sci => sci.Id == item.Id);
                    if (existingItem != null)
                    {
                        _context.Entry(existingItem).CurrentValues.SetValues(item);
                    }
                }
            }

            // 重新计算合同总金额
            existingContract.TotalAmount = existingContract.SalesContractItems.Sum(sci => sci.TotalAmount);
            existingContract.UnpaidAmount = existingContract.TotalAmount - existingContract.ReceivedAmount;

            await _context.SaveChangesAsync();
            return true;
        }

        public async Task<bool> ApproveSalesContractAsync(int id, int approvedBy)
        {
            var contract = await _context.SalesContracts.FindAsync(id);
            if (contract == null)
            {
                return false;
            }

            // 检查合同状态，如果不是待审核则不允许审核
            if (contract.Status != 0)
            {
                throw new Exception("只有待审核的合同才能审核");
            }

            // 更新合同状态
            contract.Status = 1;
            contract.ApprovedBy = approvedBy;
            contract.ApprovedTime = DateTime.Now;

            await _context.SaveChangesAsync();
            return true;
        }

        public async Task<bool> TerminateSalesContractAsync(int id, int terminatedBy, string reason)
        {
            var contract = await _context.SalesContracts.FindAsync(id);
            if (contract == null)
            {
                return false;
            }

            // 检查合同状态，如果不是已审核则不允许终止
            if (contract.Status != 1)
            {
                throw new Exception("只有已审核的合同才能终止");
            }

            // 更新合同状态
            contract.Status = 2;
            contract.TerminationReason = reason;
            contract.TerminatedBy = terminatedBy;
            contract.TerminatedTime = DateTime.Now;

            await _context.SaveChangesAsync();
            return true;
        }

        public async Task<bool> DeleteSalesContractAsync(int id)
        {
            var contract = await _context.SalesContracts
                .Include(sc => sc.SalesContractItems)
                .FirstOrDefaultAsync(sc => sc.Id == id);

            if (contract == null)
            {
                return false;
            }

            // 检查合同状态，如果已审核则不允许删除
            if (contract.Status == 1)
            {
                throw new Exception("已审核的合同不能删除");
            }

            // 删除合同明细
            _context.SalesContractItems.RemoveRange(contract.SalesContractItems);

            // 删除合同
            _context.SalesContracts.Remove(contract);

            await _context.SaveChangesAsync();
            return true;
        }

        public async Task<List<SalesContract>> SearchSalesContractsAsync(string keyword = null, int? customerId = null, int? status = null)
        {
            var query = _context.SalesContracts
                .Include(sc => sc.Customer)
                .AsQueryable();

            if (!string.IsNullOrEmpty(keyword))
            {
                query = query.Where(sc => sc.ContractCode.Contains(keyword) || sc.ContractName.Contains(keyword));
            }

            if (customerId.HasValue)
            {
                query = query.Where(sc => sc.CustomerId == customerId.Value);
            }

            if (status.HasValue)
            {
                query = query.Where(sc => sc.Status == status.Value);
            }

            return await query.ToListAsync();
        }
    }
}